package team.hyznrj.studentsys.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import team.hyznrj.studentsys.dao.mapper.PovertyMessageMapper;
import team.hyznrj.studentsys.entity.PovertyMessage;
import team.hyznrj.studentsys.entity.PovertyMessageExample;
import team.hyznrj.studentsys.entity.PovertyMessageExample.Criteria;
import team.hyznrj.studentsys.entity.PovertySearchForm;
import team.hyznrj.studentsys.exception.AuthenticationOnFlagException;
import team.hyznrj.studentsys.exception.DataNullException;
import team.hyznrj.studentsys.service.PovertyService;
import team.hyznrj.studentsys.utils.ValueUtil;

@Service
public class PovertyServiceImpl implements PovertyService {
	@Autowired
	PovertyMessageMapper mapper;
	@Value("${PovertyStr}")
	private String POVERTY_LEVEL_STR;
	String[] valueCache=null;
	public String[] getLevelValue(){
		if(valueCache==null){
			valueCache = POVERTY_LEVEL_STR.split("@");
		}
		return valueCache;
	}
	@Override
	public int getPovertyLevelIdByString(String str) {
		// 特殊困难@比较困难@一般困难
		String[] levelValue = getLevelValue();
		int val = -1;
		for (int i = 0; i < levelValue.length; i++) {
			if (str.equals(levelValue[i])) {
				val = i + 1;
				break;
			}
		}
		return val;
	}
	

	@Override
	public String getPovertyLevelStringById(int id) {
		String[] levelValue = getLevelValue();
		if(id<levelValue.length&&id>=0){
			return levelValue[id];
		}else{
			return null;
		}
	}
	@Override
	@Transactional
	public int savePovertyMessage(List<PovertyMessage> list) {
		if(list==null){
			throw new DataNullException("导入的贫困信息为空");
		}
		for(PovertyMessage msg:list){
			mapper.insert(msg);
		}
		return list.size();
	}
	public List<PovertyMessage> listPovertyMessageByForm(PovertySearchForm form){
		if(StringUtils.isEmpty(form.getFlag())){
			throw new AuthenticationOnFlagException();
		}
		/*条件*/
		PovertyMessageExample example=new PovertyMessageExample();
		Criteria criteria = example.createCriteria();
		if(form.getYearId()!=null){
			criteria.andAcademicYearsEqualTo(form.getYearId());
		}
		criteria.andFlagLike(ValueUtil.getIndexFromFlag(form.getFlag(), 0,1)+"%");
		return mapper.selectByExample(example);
		
	}
}
